package com.game.center.service;

import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.game.center.common.CenterServerErrorCode;
import com.game.center.messages.response.PlayerLoginResponseVo;
import com.game.center.messages.response.vo.PlayerRoleVo;
import com.game.center.service.manager.AccountLoginManager;
import com.game.center.messages.request.LoginCodeRequestParam;
import com.game.center.messages.request.LoginRequestParam;
import com.game.framework.common.model.AccountToken;
import com.game.framework.common.utils.JWTUtil;
import com.game.framework.dao.RoleDao;
import com.game.framework.dao.entity.RoleEntity;
import com.game.framework.dao.entity.UserInfoEntity;
import com.game.framework.dao.mapper.RoleMapper;
import com.game.framework.dao.mapper.UserInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

	private static final String MD5_ENCODE = "utf8";

	@Autowired
	protected RoleDao roleDao;

	//@Autowired
	//protected AccountMapper accountMapper;

	@Autowired
	protected RoleMapper roleMapper;

	@Autowired
	protected UserInfoMapper userInfoMapper;

	private AccountLoginManager loginManager = new AccountLoginManager();

	//private AccountRegisterManager registerManager = new AccountRegisterManager();

	/**
	 * <p>
	 * Description:使用算法，根据用户名生成一个唯的ID
	 * </p>
	 */
	public String generatePassword(String password) {
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		String newPassword = encoder.encode(password);
		//String newValue = MD5Utils.md5Hex(password, MD5_ENCODE);
		//String newPassword = MD5Utils.md5Hex((password + "_" + newValue), MD5_ENCODE);
		return newPassword;
	}

	/**
	 * 根据用户名和密码登陆
	 *
	 * @param loginRequestParam
	 * @return
	 * @author  zcq
	 * @date 2019年8月29日 下午8:24:29
	 */
	@Override
	public PlayerLoginResponseVo login(LoginRequestParam loginRequestParam) {
		String account = loginRequestParam.getAccount();
		String password = this.generatePassword(loginRequestParam.getPassword());
		UserInfoEntity userInfoEntity = userInfoMapper.selectByPhone(account);
		if (userInfoEntity != null) {
			boolean isRight = loginManager.isPasswordRight(password, userInfoEntity.getPassword());
			if (isRight) {
				PlayerLoginResponseVo playerLoginResponseVo = new PlayerLoginResponseVo();
				playerLoginResponseVo.setAccount(userInfoEntity.getPhone());
				playerLoginResponseVo.setUserId(userInfoEntity.getUserCode());
				BeanUtils.copyProperties(userInfoEntity, playerLoginResponseVo);
				String token = createUserToken(userInfoEntity.getPhone(), userInfoEntity.getUserCode());
				playerLoginResponseVo.setToken(token);
				List<RoleEntity> roleEntityList = roleMapper.selectByUserId((long)userInfoEntity.getUserCode());
				if(CollectionUtils.isNotEmpty(roleEntityList)){
					for(RoleEntity roleEntity : roleEntityList) {
						PlayerRoleVo playerRoleVo = new PlayerRoleVo();
						BeanUtils.copyProperties(roleEntity, playerRoleVo);
						playerLoginResponseVo.getRoles().add(playerRoleVo);
					}
				}
				log.debug("user {} 登陆成功", loginRequestParam.getAccount());
				return playerLoginResponseVo;
			} else {
				//返回登陆异常
				throw CenterServerErrorCode.PASSWORD_ERROR.newException("登陆账号:{}", loginRequestParam.getAccount());
			}
		} else {
			throw CenterServerErrorCode.ACCOUNT_NOT_EXIST.newException("登陆账号:{}", loginRequestParam.getAccount());
		}
	}

	@Override
	public PlayerLoginResponseVo loginCode(LoginCodeRequestParam loginParam) {
		String account = loginParam.getAccount();
		UserInfoEntity userInfoEntity = userInfoMapper.selectByPhone(account);
		if (userInfoEntity != null) {
			boolean isRight = loginManager.isSmsCodeRight(loginParam.getCode(), account);
			if (isRight) {
				PlayerLoginResponseVo playerLoginResponseVo = new PlayerLoginResponseVo();
				playerLoginResponseVo.setAccount(userInfoEntity.getPhone());
				playerLoginResponseVo.setUserId(userInfoEntity.getUserCode());
				BeanUtils.copyProperties(userInfoEntity, playerLoginResponseVo);
				String token = createUserToken(userInfoEntity.getPhone(), userInfoEntity.getUserCode());
				playerLoginResponseVo.setToken(token);
				List<RoleEntity> roleEntityList = roleMapper.selectByUserId((long)userInfoEntity.getUserCode());
				if(CollectionUtils.isNotEmpty(roleEntityList)){
					for(RoleEntity roleEntity : roleEntityList) {
						PlayerRoleVo playerRoleVo = new PlayerRoleVo();
						BeanUtils.copyProperties(roleEntity, playerRoleVo);
						playerLoginResponseVo.getRoles().add(playerRoleVo);
					}
				}else {
					RoleEntity roleEntity = createPlayerRole(userInfoEntity);
					roleDao.saveOrUpdate(roleEntity, roleEntity.getId());
					PlayerRoleVo playerRoleVo = new PlayerRoleVo();
					BeanUtils.copyProperties(roleEntity, playerRoleVo);
					playerLoginResponseVo.getRoles().add(playerRoleVo);
				}
				log.debug("user {} 登陆成功", loginParam.getAccount());
				return playerLoginResponseVo;
			} else {
				//返回登陆异常
				throw CenterServerErrorCode.PASSWORD_ERROR.newException("登陆账号:{}", loginParam.getAccount());
			}
		} else {
			throw CenterServerErrorCode.ACCOUNT_NOT_EXIST.newException("登陆账号:{}", loginParam.getAccount());
		}
	}

	@Override
	public String createUserToken(String account, Integer userId) {
		AccountToken accountToken = new AccountToken();
		accountToken.setAccount(account);
		accountToken.setUserId(userId);
		accountToken.setExpireDays(30);
		return JWTUtil.createToken(accountToken);
	}

	@Override
	public Integer selectUserCount(String phone) {
		return userInfoMapper.selectCountByPhone(phone);
	}

	@Override
	public RoleEntity createPlayerRole(UserInfoEntity userInfo) {
		RoleEntity roleEntity = new RoleEntity();
		roleEntity.setRoleId(System.currentTimeMillis()+ RandomUtils.nextLong());
		roleEntity.setUserId(userInfo.getUserCode());
		roleEntity.setNickName(userInfo.getNickName());
		roleEntity.setHeadImg(userInfo.getHeadimgUrl());
		roleEntity.setCreateTime(roleEntity.getCreateTime());
		roleEntity.setLastLoginTime(new Date());
		roleEntity.setNewCreate(true);
		roleMapper.insert(roleEntity);
		roleEntity = roleMapper.selectByRoleId(roleEntity.getRoleId());
		return roleEntity;
	}

	/*
	@Override
	public PlayerLoginResponseVo register(RegisterRequestParam registerParam, String loginIp) {
		registerManager.checkAccount(registerParam.getAccount());
		registerManager.checkPassword(registerParam.getPassword());
		AccountEntity accountEntity = accountMapper.selectByAccount(registerParam.getAccount());
		if(accountEntity != null){
			return null;
		}
		String password = this.generatePassword(registerParam.getPassword());
		accountEntity = registerManager.buildAccount(registerParam.getAccount(), password, loginIp);
		accountMapper.insert(accountEntity);
		accountEntity = accountMapper.selectByAccount(accountEntity.getAccount());
		accountDao.saveOrUpdate(accountEntity, accountEntity.getId());
//		List<RoleEntity> roleEntityList = roleMapper.selectByUserId(accountEntity.getUserId());
//		if(CollectionUtils.isNotEmpty(roleEntityList)){
//			return null;
//		}
		RoleEntity roleEntity = createPlayerRole(accountEntity);
		roleDao.saveOrUpdate(roleEntity, roleEntity.getId());
		PlayerLoginResponseVo voPlayer = new PlayerLoginResponseVo();
		voPlayer.setAccount(accountEntity.getAccount());
		voPlayer.setUserId(accountEntity.getId());
		voPlayer.setCreateTime(accountEntity.getCreateTime());
		String token = createUserToken(accountEntity);
		voPlayer.setToken(token);
		PlayerRoleVo voRole = new PlayerRoleVo();
		BeanUtils.copyProperties(roleEntity, voRole);
		voPlayer.getRoles().add(voRole);
		log.info("注册成功:{},{}", accountEntity.getId(), accountEntity);
		return voPlayer;
	}

	@Override
	public AccountEntity selectAccount(String account) {
		AccountEntity accountEntity = accountMapper.selectByAccount(account);
		return accountEntity;
	}

	@Override
	public RoleEntity createPlayerRole(AccountEntity accountEntity) {
		RoleEntity roleEntity = new RoleEntity();
		roleEntity.setRoleId(System.currentTimeMillis()+ RandomUtils.nextLong());
		roleEntity.setUserId(accountEntity.getUserId());
		roleEntity.setNickName(accountEntity.getAccount());
		roleEntity.setCreateTime(roleEntity.getCreateTime());
		roleEntity.setLastLoginTime(new Date());
		roleEntity.setNewCreate(true);
		roleMapper.insert(roleEntity);
		roleEntity = roleMapper.selectByRoleId(roleEntity.getRoleId());
		return roleEntity;
	}

	@Override
	public void logout(long userId) {
		AccountEntity accountEntity = accountMapper.selectByUserId(userId);
		if(accountEntity != null){
			accountMapper.updateById(accountEntity);
			accountDao.saveOrUpdate(accountEntity, accountEntity.getId());
		}
		List<RoleEntity> roleEntityList = roleMapper.selectByUserId(userId);
		if(CollectionUtils.isNotEmpty(roleEntityList)){
			for (RoleEntity roleEntity : roleEntityList){
				roleEntity.setLastLogoutTime(new Date());
				roleMapper.updateById(roleEntity);
				roleDao.saveOrUpdate(roleEntity, roleEntity.getId());
			}
		}
	}
	*/
}
